package gold.digger;

import gold.utils.InputUtil;

import java.util.*;

/**
 * Created by fanzhenyu02 on 2021/12/10.
 * common problem solver template.
 */
public class LCJZOF112 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {

        public Map<String, Integer> memo = new HashMap<>();
        int m, n;
        int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

        public int longestIncreasingPath(int[][] matrix) {
            m = matrix.length;
            n = matrix[0].length;
            boolean[][] visited = new boolean[m][n];

            int ans = 1;
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    visited[i][j] = true;
                    ans = Math.max(ans, dfs(matrix, visited, i, j));
                    visited[i][j] = false;
                }
            }

            return ans;
        }

        public int dfs(int[][] matrix, boolean[][] visited, int i, int j) {
            String key = i + "_" + j;
            if (memo.containsKey(key)) return memo.get(key);

            // travel four directions
            int curLongestLen = 1;
            for (int[] direction : directions) {
                if (i + direction[0] < 0 || i + direction[0] >= m || j + direction[1] < 0 || j + direction[1] >= n
                        || visited[i + direction[0]][j + direction[1]] || matrix[i][j] >= matrix[i + direction[0]][j + direction[1]])
                    continue;
                visited[i + direction[0]][j + direction[1]] = true;
                int curDirectionLen = dfs(matrix, visited, i + direction[0], j + direction[1]) + 1;
                curLongestLen = Math.max(curLongestLen, curDirectionLen);
                visited[i + direction[0]][j + direction[1]] = false;
            }

            memo.put(key, curLongestLen);
            return curLongestLen;
        }
    }

    public void run() {
        System.out.println(new Solution().longestIncreasingPath(InputUtil.toDoubleIntegerArray("[[9,9,4],[6,6,8],[2,1,1]]")));
        System.out.println(new Solution().longestIncreasingPath(InputUtil.toDoubleIntegerArray("[[3,4,5],[3,2,6],[2,2,1]]")));
        System.out.println(new Solution().longestIncreasingPath(InputUtil.toDoubleIntegerArray("[[1]]")));
    }

    public static void main(String[] args) throws Exception {
        LCJZOF112 an = new LCJZOF112();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
